package reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

public class test12 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {

        Class c = Class.forName("reflection.student1");
        //通过反射的Class获取所有注解
        Annotation[] annotations = c.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //获取一个注解及其参数
        TableName tableName =(TableName) c.getAnnotation(TableName.class);
        String value = tableName.value();
        System.out.println(value);

        //获取Field注解
        Field filed = c.getDeclaredField("id");
        FiledName filedName =filed.getAnnotation(FiledName.class);
        System.out.println(filedName.columnName());
        System.out.println(filedName.type());
        System.out.println(filedName.length());
    }
}

//假设数据库中student类对应的表为db_student
@TableName("db_student")
class student1{
    @FiledName(columnName = "db_id",type = "int",length = 10)
    private int id;
    @FiledName(columnName = "db_name",type = "varchar",length = 10)
    private String name;
    @FiledName(columnName = "db_age",type = "int",length = 10)
    private int age;

    public student1() {
    }

    public student1(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

//标记类对应的表名，value为表明，作用在类上，运行时生效
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableName{
    String value();
}
//标记属性对应的字段，参数有字段名，字段类型，字段长度，作用在属性上，运行时生效
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FiledName{
    String columnName();
    String type();
    int length();
}